<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--风险分析对象数据-->
      <el-col :span="6" :xs="24">
        <div class="head-container">
          <el-input
            v-model="keyValue"
            placeholder="请输入风险分析对象名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="targetOptions"
            :props="{ label: 'riskTargetName', child: '' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="targetShowRef"
            node-key="riskTargetId"
            :current-node-key="checkNode"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template class="custom-tree-node" #default="{ node, data }">
              <div
                style="
                  display: flex;
                  align-items: flex-start;
                  justify-content: space-between;
                  width: 100%;
                "
              >
                <span style="padding-left: 4px">{{ node.label }}</span>
              </div>
            </template>
          </el-tree>
        </div>
      </el-col>

      <!--风险分析单元数据-->
      <el-col :span="18" :xs="24">
        <el-table v-loading="loading" :data="unitShowList">
          <el-table-column
            label="风险分析单元名称"
            align="center"
            key="riskUnitName"
            prop="riskUnitName"
          />
          <el-table-column
            label="责任部门"
            align="center"
            key="hazardDep"
            prop="hazardDep"
          />
          <el-table-column
            label="责任人"
            align="center"
            key="hazardLiablePerson"
            prop="hazardLiablePerson"
          />
          <el-table-column label="状态" align="center" prop="riskUnitStatus" width="160">
            <template #default="scope">
              <el-switch
                v-model="scope.row.riskUnitStatus"
                active-value="0"
                inactive-value="1"
                :before-change="beforeChange"
              ></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="创建时间" align="center" prop="createdAt" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="150"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="停工" placement="top" v-if="scope.row.userId !== 1">
                <el-button
                  link
                  type="primary"
                  @click="handleStop(scope.row)"
                  v-hasPermi="['system:user:edit']"
                  >停工</el-button
                >
              </el-tooltip>
              <el-tooltip content="停工历史" placement="top">
                <el-button link type="primary" @click="handleHistory(scope.row)"
                  >停工历史</el-button
                >
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!--停工检修历史记录对话框-->
    <el-dialog :title="title" v-model="open" width="60%" append-to-body>
      <el-table v-loading="loading" :data="historyDataList">
        <el-table-column label="停工原因" align="center" prop="stopReason" />

        <el-table-column label="检修开始时间" align="center" prop="stopStartTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.stopStartTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="检修结束时间" align="center" prop="stopEndTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.stopEndTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.current"
        v-model:limit="queryParams.size"
        @pagination="getHistoryList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelStopHistory">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--设置停工检修对话框-->
    <el-dialog :title="titleDownTime" v-model="openDownTime" width="60%" append-to-body>
      <el-form :model="stopForm" :rules="stopRules" ref="stopRef" label-width="80px">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="检修开始时间:" label-width="140px" prop="stopStartTime">
              <el-date-picker
                v-model="stopForm.stopStartTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="开始日期"
                type="datetime"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="检修结束时间:" label-width="140px" prop="stopEndTime">
              <el-date-picker
                v-model="stopForm.stopEndTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="结束日期"
                type="datetime"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="停工检修原因:" label-width="140px" prop="stopReason">
          <el-input
            type="textarea"
            :rows="3"
            v-model="stopForm.stopReason"
            placeholder="请输入原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitStopForm">确 定</el-button>
          <el-button @click="cancelStop">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Unit">
import { listTarget } from "@/api/prevent/risk/target";
import { listUnit, listStop, addStop } from "@/api/prevent/risk/unit";

import { listDutyUser } from "@/api/prevent/hidden/dutyUser";
const { proxy } = getCurrentInstance();

const loading = ref(true);
const keyValue = ref("");

const unitList = ref(undefined);
const unitShowList = ref([]);

const targetOptions = ref(undefined);
const checkNode = ref("");
const checkNodeHazardCode = ref("");
const checkNodeHazardLevelId = ref(undefined);

const liablePersonOptions = ref([]);
const titleDownTime = ref("");
const total = ref(0);
const openDownTime = ref(false);
const title = ref("");
const open = ref(false);
const historyDataList = ref([]);
const data = reactive({
  stopForm: {},
  queryParams: {
    current: 1,
    size: 10,
  },

  stopRules: {
    stopReason: [
      { required: true, message: "停用原因必须填写！", trigger: "blur" },
      { min: 2, max: 2000, message: "长度必须介于 2 和 2000 之间", trigger: "blur" },
    ],
    stopStartTime: [
      { required: true, message: "停用开始时间必须选择！", trigger: "blur" },
    ],
    stopEndTime: [{ required: true, message: "停用结束时间必须选择！", trigger: "blur" }],
  },
});

const { stopForm, stopRules, queryParams } = toRefs(data);

/** 根据名称筛选风险分析对象 */
watch(keyValue, (val) => {
  proxy.$refs["targetShowRef"].filter(val);
});

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.riskTargetName.indexOf(value) !== -1;
};

/** 节点单击事件 */
function handleNodeClick(data) {
  checkNode.value = data.riskTargetId;
  checkNodeHazardCode.value = data.hazardCode;
  checkNodeHazardLevelId.value = data.hazardLevelId;
  changeUnitShow();
}
/** 查询风险分析对象下拉树结构 */
function getTargetList() {
  listTarget().then((response) => {
    targetOptions.value = response.data;
    //console.log(response.data[0]);
    if (response.data.length > 0) {
      checkNode.value = response.data[0].riskTargetId;
      checkNodeHazardCode.value = response.data[0].hazardCode;
      checkNodeHazardLevelId.value = response.data[0].hazardLevelId;
    }
  });
}

/** 更新风险分析单元呈现数据 */
function changeUnitShow() {
  unitShowList.value = [];
  unitList.value.filter((item, i, arr) => {
    if (checkNode.value == "" || checkNode.value == null) {
      setTimeout(() => {
        if (item.riskTargetId == checkNode.value) {
          unitShowList.value.push(item);
        }
      }, 500);
    } else {
      if (item.riskTargetId == checkNode.value) {
        unitShowList.value.push(item);
      }
    }
  });
}

/** 获取风险分析单元列表 */
function getUnitList() {
  loading.value = true;
  listUnit().then((response) => {
    unitList.value = response.data;
    changeUnitShow();
  });
  loading.value = false;
}

/** 获取责任人数据列表 */
async function getCheckUserList() {
  listDutyUser().then((response) => {
    liablePersonOptions.value = response.data;
  });
}
/** 处理停工检修历史记录 */
function handleHistory(row) {
  open.value = true;
  title.value = "停工检修记录";
  queryParams.value.riskUnitId = row.riskUnitId;
  getHistoryList();
}

/** 重置停工检修表单 */
function resetStop() {
  stopForm.value = {};
  proxy.resetForm("stopRef");
}

/** 取消停工检修对话框 */
function cancelStop() {
  openDownTime.value = false;
  resetStop();
}

/** 取消停工检修历史记录对话框 */
function cancelStopHistory() {
  open.value = false;
}
/** 处理分析停工检修状态 */
function handleStop(row) {
  if (row.riskUnitStatus === "0") {
    stopForm.value.riskUnitId = row.riskUnitId;
    stopForm.value.hazardCode = row.hazardCode;
    openDownTime.value = true;

    titleDownTime.value = "停工设置";
  } else {
    proxy.$modal.msgError("停工状态不能修改！");
  }
}

/** 单元状态阻止 */
function beforeChange() {
  proxy.$modal.msgError("状态不能修改,如需更改请停工操作！");
  return false;
}

/** 提交停工检修 */
function submitStopForm() {
  proxy.$refs["stopRef"].validate((valid) => {
    if (valid) {
      addStop(stopForm.value).then((response) => {
        proxy.$modal.msgSuccess("停工检修设置成功");
        openDownTime.value = false;
      });
    }
  });
}

/** 获取停工检修记录 */
function getHistoryList() {
  console.log(queryParams.value);
  listStop(queryParams.value).then((res) => {
    historyDataList.value = res.data.dataList;
    total.value = res.data.totalNum;
  });
}
/**初始化调用 */
getCheckUserList();

getTargetList();
getUnitList();
</script>
<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-tree :deep(.el-tree-node__content) {
  height: 38px;
}
</style>
